/**
 * By Alpha
 * Author: alixez <alixe.z@foxmail.com>
 * Date: 2017/11/3
 */
/* global window */

import moment from 'moment';
import config from '../config';

const { prefix } = config;

export const OFFICIAL_ACCESS_TOKEN = `${prefix}official_access_token`;

export default class AccessToken {

  constructor () {
    this.__tokenString = '';
    this.__expireAt = moment().add(30, 'm').valueOf();
  }

  create ({ tokenString, expireAt }) {
    if (!this.loadFromDisk()) {
      this.__tokenString = tokenString;
      this.__expireAt = expireAt || moment().add(30, 'm').valueOf();
      this.saveToDisk();
    } else if (this.__expireAt >= moment().valueOf()) {
      this.__tokenString = tokenString;
      this.__expireAt = expireAt || moment().add(30, 'm').valueOf();
      this.saveToDisk();
    }
  }

  clear () {
    this.__tokenString = null;
    this.__expireAt = null;

    window.localStorage.removeItem(OFFICIAL_ACCESS_TOKEN);
  }


  update ({ tokenString, expireAt }) {
    this.__tokenString = tokenString;
    this.__expireAt = expireAt || moment().add(30, 'm').valueOf();
    this.saveToDisk();
  }

  setTokenString (tokenString) {
    this.__tokenString = tokenString;
  }

  saveToDisk () {
    const token = {
      tokenString: this.__tokenString,
      expireAt: this.__expireAt,
    };
    // window.localStorage.setItem('unite_test', '123123');
    window.localStorage.setItem(OFFICIAL_ACCESS_TOKEN, JSON.stringify(token));
  }

  loadFromDisk () {
    let token = null;
    const tokenFromDisk = window.localStorage.getItem(OFFICIAL_ACCESS_TOKEN);
    if (tokenFromDisk) {
      token = JSON.parse(tokenFromDisk);
    }

    if (token && token.tokenString && token.expireAt ) {
      this.__expireAt = token.expireAt;
      this.__tokenString = token.tokenString;

      return true;
    }

    return false;
  }

  validated () {
    if (this.__tokenString) {
      return true;
    }

    return false;
  }

  expireAt () {
    return this.__expireAt;
  }

  valueOf () {
    return this.__tokenString;
  }
}
